# 导入json模块，用于处理JSON数据
import json

# 导入sys模块，用于标准输入输出
import sys

# 从typing模块导入类型注解
from typing import Any, Dict, List


# 定义天气服务器类
class WeatherServer:
    """天气服务器类"""

    # 构造函数，初始化工具字典
    def __init__(self):
        # 定义支持的工具及其元数据和输入模式
        self.tools = {
            "com.example.weather/current": {
                "name": "com.example.weather/current",
                "title": "获取当前天气",
                "description": "获取指定城市的当前天气信息",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "location": {"type": "string", "description": "城市名称"},
                        "units": {
                            "type": "string",
                            "enum": ["metric", "imperial"],
                            "default": "metric",
                        },
                    },
                    "required": ["location"],
                },
            },
            "com.example.weather/forecast": {
                "name": "com.example.weather/forecast",
                "title": "天气预报",
                "description": "获取未来几天的天气预报",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "location": {"type": "string", "description": "城市名称"},
                        "days": {
                            "type": "integer",
                            "minimum": 1,
                            "maximum": 7,
                            "default": 3,
                        },
                    },
                    "required": ["location"],
                },
            },
        }

    # 处理JSON-RPC请求的方法
    def handle_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
        """处理JSON-RPC请求"""
        # 获取请求的方法名
        method = request.get("method")
        # 获取请求的id
        request_id = request.get("id")
        # 获取请求参数，默认为空字典
        params = request.get("params", {})

        # 如果方法为initialize，返回初始化响应
        if method == "initialize":
            # 初始化响应
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "result": {
                    "protocolVersion": "2025-06-18",
                    "capabilities": {
                        "tools": {"listChanged": True},
                        "resources": {},
                    },
                    "serverInfo": {"name": "weather-server", "version": "1.0.0"},
                },
            }

        # 如果方法为tools/list，返回工具列表
        elif method == "tools/list":
            # 工具列表响应
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "result": {"tools": list(self.tools.values())},
            }

        # 如果方法为tools/call，调用指定工具
        elif method == "tools/call":
            # 获取工具名称
            name = params.get("name")
            # 获取工具参数
            arguments = params.get("arguments", {})

            try:
                # 调用工具方法
                result = self.call_tool(name, arguments)
                # 返回调用结果
                return {
                    "jsonrpc": "2.0",
                    "id": request_id,
                    "result": {"content": result},
                }
            # 捕获异常，返回错误信息
            except Exception as e:
                return {
                    "jsonrpc": "2.0",
                    "id": request_id,
                    "error": {"code": -32603, "message": str(e)},
                }

        # 其他未知方法，返回方法未找到错误
        else:
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "error": {"code": -32601, "message": f"Method {method} not found"},
            }

    # 工具调用方法，根据工具名称和参数执行相应操作
    def call_tool(self, name: str, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
        """执行工具调用"""

        # 如果调用的是获取当前天气工具
        if name == "com.example.weather/current":
            # 获取城市名称，默认为“未知城市”
            location = arguments.get("location", "未知城市")
            # 获取温度单位，默认为“metric”
            units = arguments.get("units", "metric")

            # 模拟天气数据获取
            temperature = 72 if units == "imperial" else 22
            temp_unit = "°F" if units == "imperial" else "°C"

            # 返回当前天气文本信息
            return [
                {
                    "type": "text",
                    "text": f"{location}当前天气：晴天，温度{temperature}{temp_unit}，湿度65%",
                }
            ]

        # 如果调用的是天气预报工具
        elif name == "com.example.weather/forecast":
            # 获取城市名称，默认为“未知城市”
            location = arguments.get("location", "未知城市")
            # 获取预报天数，默认为3天
            days = arguments.get("days", 3)

            # 模拟天气预报数据
            forecast = f"{location}未来{days}天天气预报：\n"
            # 循环生成每一天的天气信息
            for i in range(days):
                forecast += f"第{i+1}天：晴天，温度20-25°C\n"

            # 返回天气预报文本信息
            return [{"type": "text", "text": forecast}]

        # 未知工具，抛出异常
        else:
            raise ValueError(f"未知工具：{name}")


# 主函数，程序入口
def main():
    """主函数"""
    # 创建WeatherServer实例
    server = WeatherServer()

    # 在标准错误输出服务器启动提示
    print("🌤️ 天气服务器已启动，等待连接...", file=sys.stderr)

    # 从标准输入读取请求，向标准输出发送响应
    for line in sys.stdin:
        try:
            # 解析输入的JSON请求
            request = json.loads(line.strip())
            # 处理请求，获取响应
            response = server.handle_request(request)
            # 输出响应的JSON字符串
            print(json.dumps(response, ensure_ascii=False))
            # 刷新标准输出缓冲区
            sys.stdout.flush()
        # 捕获JSON解析错误
        except json.JSONDecodeError:
            # 输出解析错误响应
            print(
                json.dumps(
                    {
                        "jsonrpc": "2.0",
                        "id": None,
                        "error": {"code": -32700, "message": "Parse error"},
                    },
                    ensure_ascii=False,
                )
            )
            # 刷新标准输出缓冲区
            sys.stdout.flush()


# 判断是否为主模块，若是则执行main函数
if __name__ == "__main__":
    main()
